package san.java.arrays_04;

/**
 * 数组中涉及的常见算法
 *  1. 求数组中元素的最大值, 最小值, 总和, 平均数
 *  2. 数组的复制, 反转
 *  3. 数组元素的排序
 */

public class algorithms {

    /**
     * 求最大值
     * @return
     */
    public static int max(int[] a) {
        int res = Integer.MIN_VALUE;
        for (int i = 0; i < a.length; i++) {
            if (a[i] > res)
                res = a[i];
        }

        return res;
    }

    /**
     * 最小值
     * @param a
     * @return
     */
    public static int min(int[] a) {
        int res = Integer.MAX_VALUE;
        for (int i = 0; i < a.length; i++) {
            if (a[i] < res)
                res = a[i];
        }

        return res;
    }

    /**
     * 数组复制
     * @param a
     * @return
     */
    public static int[] copy(int[] a) {
        int[] res = new int[a.length];
        for (int i = 0; i < a.length; i++)
            res[i] = a[i];

        return res;
    }

    /**
     * 数组反转
     * @param a
     * @return
     */
    public static void reverse(int[] a) {
        Integer i = 0, j = a.length - 1;
        while (i < j) {
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i++;
            j--;
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{4, 2, 7, 1, 3, 5};

        // 1. 最大值
        System.out.println("最大值: " + max(arr));

        // 2. 最小值
        System.out.println("最小值: " + min(arr));

        // 3. 复制
        int[] carr = copy(arr);
        System.out.println("carr: ");
        for (int i = 0; i < carr.length; i++) {
            System.out.printf("%d ", carr[i]);
        }

        System.out.println("\n原始的arr: ");
        for (int i = 0; i < arr.length; i++) {
            System.out.printf("%d ", arr[i]);
        }

        // 4. 反转
        System.out.println("\n反转后的arr: ");
        reverse(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.printf("%d ", arr[i]);
        }


    }
}
